<template>
  <div class="config-panel">
    <h4>{{ title }}</h4>
    <el-form label-position="top">
      <el-form-item label="是否启用">
        <el-switch v-model="config.enabled"></el-switch>
      </el-form-item>

      <div v-if="config.enabled">
        <el-form-item label="图片设置 (建议尺寸: 750px*340px)">
          <draggable v-model="config.list" handle=".drag-handle" animation="150">
            <div v-for="(item, index) in config.list" :key="index" class="config-item">
              <i class="el-icon-rank drag-handle" title="拖拽排序"></i>
              <p>图片 {{ index + 1 }}</p>
              <el-form-item label="图片名称"><el-input v-model="item.name" placeholder="请输入名称"></el-input></el-form-item>
              <el-form-item label="图片"><image-upload v-model="item.url" /></el-form-item>
              <el-form-item label="跳转链接"><el-input v-model="item.link" placeholder="请输入跳转链接"></el-input></el-form-item>
              <el-button type="danger" size="mini" @click="removeItem(index)" class="delete-btn" icon="el-icon-delete" circle></el-button>
            </div>
          </draggable>
          <el-button type="primary" @click="addItem" v-if="!config.list || config.list.length < 5">添加图片</el-button>
        </el-form-item>
      </div>
    </el-form>
  </div>
</template>

<script>
import ImageUpload from '@/components/ImageUpload';
import draggable from 'vuedraggable';

export default {
  name: "BannerConfig",
  components: { ImageUpload, draggable },
  props: ['value', 'title'],
  computed: {
    config: {
      get() {
        if (this.value.enabled === undefined) this.$set(this.value, 'enabled', true);
        if (!this.value.list) this.$set(this.value, 'list', []);
        return this.value;
      },
      set(newValue) { this.$emit('input', newValue); }
    }
  },
  methods: {
    addItem() {
      // 兼容旧数据中的 image 字段
      this.config.list.push({ name: '', url: '', link: '', image: '' });
    },
    removeItem(index) {
      this.config.list.splice(index, 1);
    }
  }
}
</script>

<style scoped>
.config-panel { border: 1px solid #f0f0f0; padding: 15px; border-radius: 4px; margin-bottom: 20px; }
h4 { margin-top: 0; margin-bottom: 20px; }
.config-item { position: relative; border: 1px dashed #d9d9d9; padding: 15px; padding-top: 40px; margin-bottom: 10px; border-radius: 4px; }
.drag-handle { position: absolute; top: 10px; left: 10px; cursor: move; font-size: 20px; color: #999; }
.delete-btn { position: absolute; top: 5px; right: 5px; }
</style>
